package park.another_prospect;

import java.util.*;

/**
 * Created by olinchy on 03/07/2017.
 */
public class ParkingLot
{
    private Timer timer = new Timer(true);

    private List<ParkingLane> lanes = new LinkedList<ParkingLane>();
    private int currentFreeSpot;
    private int currentLane = 0;

    public ParkingLot(int spots, int lanes)
    {
        createLanes(lanes);
        currentFreeSpot = spots;

        timer.schedule(new TimerTask()
        {
            @Override
            public void run()
            {
                System.out.println(ParkingLot.this.toString());
            }
        }, 10000, 10000);
    }

    private void createLanes(int lanes)
    {
        for (int i = 0; i < lanes; i++)
        {
            this.lanes.add(new ParkingLane(this, i));
        }
    }

    public void park(final Car car)
    {
        ParkingLane lane = chooseLane();
        lane.add(new CarObserver(car)
        {
            @Override
            public void update(Observable o, Object arg)
            {
                synchronized (ParkingLot.this)
                {
                    currentFreeSpot--;
                    System.out.println(car.toString() + " entered at:" + new Date());
                }
            }
        });
    }

    private synchronized ParkingLane chooseLane()
    {
        if (currentLane < lanes.size())
            return lanes.get(currentLane++);
        else
        {
            currentLane = 0;
            return chooseLane();
        }
    }

    public synchronized void exit(String licensePlate)
    {
        // TODO: 03/07/2017 send request to server and print cost or time consume
        currentFreeSpot++;
        System.out.println(" car " + licensePlate + " exit at " + new Date() + " cost :");
    }

    public void enter(String licensePlate)
    {
        // TODO: 03/07/2017 send request to server
    }

    public synchronized boolean isAvailable()
    {
        return currentFreeSpot > 0;
    }

    @Override
    public String toString()
    {
        return "ParkingLot{" +
                "lanes=" + Arrays.toString(lanes.toArray()) +
                ", currentFreeSpot=" + currentFreeSpot +
                '}';
    }
}
